package com.atguigu.myjuc.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
class MyCache {

    // 加入读写锁
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    volatile Map<String, String> map= new HashMap<>();

    public void write(String key, String value) {

        // 加写锁
        rwLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + " 开始写入！");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入成功！");
        } finally {
            // 释放写锁
            rwLock.writeLock().unlock();
        }
    }

    public void read(String key) {

        // 加入读锁
        rwLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + " 开始读出！");
            String value = map.get(key);
            System.out.println(Thread.currentThread().getName() + " 读出成功！" + value);
        } finally {
            // 释放读锁
            rwLock.readLock().unlock();
        }
    }
}

public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache cache = new MyCache();

        for (int i = 1; i <= 5; i++) {
            // 开启5个写线程
            int finalI = i;
            new Thread(() -> {
                cache.write(finalI + "", finalI + "");
            }, String.valueOf(i)).start();
        }

        //暂停亳秒
        try { TimeUnit.MICROSECONDS.sleep(10); } catch (Exception e) { e.printStackTrace(); }

        for (int i = 1; i <= 5; i++) {
            // 开启5个读线程
            int finalI = i;
            new Thread(() -> {
                cache.read(finalI + "");
            }, String.valueOf(i)).start();
        }
    }
}
